/**
 * @file Mutex.cpp
 *
 *  @date 2009-06-05
 *  @author hauleth
 */

#include <Bust/Threads/Mutex.hpp>
#include <pthread.h>

#include "PrivateData.hpp"

namespace bust {

Mutex::Mutex() {
	pthread_mutexattr_t mutex_attr;
	pthread_mutexattr_init( &mutex_attr );
	MutexPrivateData *pd = new MutexPrivateData();
	pthread_mutex_init( &pd->mutex, &mutex_attr );
	_data = static_cast< void * > ( pd );
}

Mutex::~Mutex() {
	MutexPrivateData *pd = static_cast< MutexPrivateData* > ( _data );
	pthread_mutex_destroy( &pd->mutex );
	delete pd;
}

bool Mutex::lock() {
	MutexPrivateData *pd = static_cast< MutexPrivateData* > ( _data );
	return pthread_mutex_lock( &pd->mutex ) == 0;
}

bool Mutex::trylock() {
	MutexPrivateData *pd = static_cast< MutexPrivateData* > ( _data );
	return pthread_mutex_trylock( &pd->mutex ) == 0;
}

bool Mutex::unlock() {
	MutexPrivateData *pd = static_cast< MutexPrivateData* > ( _data );
	int stat = pthread_mutex_unlock( &pd->mutex );
	return stat == 0;
}

}
